package com.logic.config.interceptor;

import com.comment.exception.ServiceException;
import com.logic.comment.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class ReqInterceptor implements HandlerInterceptor {
    @Resource
    private ServiceInterceptor serviceInterceptor;
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            @NotNull HttpServletResponse response,
            @NotNull Object handler
    ) throws Exception {
        request.setCharacterEncoding("utf-8");
        // 请求头
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            log.error(">>>>>请求地址>>>>>{}", request.getRequestURI());
            throw new ServiceException("请登录");
        }
        if (!JwtUtils.verify(token)) {
            throw new ServiceException("非法token");
        } else {
            JwtUtils.verifyUserToken(token);
        }
        serviceInterceptor.apply(request);
        return true;
    }

    @Override
    public void postHandle(
            @NotNull HttpServletRequest request,
            @NotNull HttpServletResponse response,
            @NotNull Object handler,
            ModelAndView modelAndView
    ) {
    }

    /**
     * 该方法也是需要当前对应的Interceptor
     * 的preHandle方法的返回值为true时才会执行。
     * 该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行，
     * 这个方法的主要作用是用于清理资源的，
     * 当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
     */
    @Override
    public void afterCompletion(
            @NotNull HttpServletRequest request,
            @NotNull HttpServletResponse response,
            @NotNull Object handler,
            Exception ex
    ) {
        // System.out.println(">>>MyInterceptor1>>>>>>>
        // 在整个请求结束之后被调用，也就是在DispatcherServlet
        // 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
